<?php
namespace App\Controllers;

use Core\Controller;
use Core\Request;
use App\Exceptions\NotFoundException;
class UserController extends Controller {
    public function index(Request $request) {
        // 模拟用户数据
        $users = [
            ['id' => 1, 'name' => 'John Doe', 'email' => 'john@example.com'],
            ['id' => 2, 'name' => 'Jane Smith', 'email' => 'jane@example.com']
        ];
        
        return $this->json(['users' => $users]);
    }
    
    public function show(Request $request) {
        $id = $request->getRouteParam('id');
        
        // 模拟查找用户
        $user = $this->findUser($id);
        
        if (!$user) {
            throw new NotFoundException('User not found');
        }
        
        return $this->json($user);
    }
    public function store(Request $request) {
        $data = $request->getBody();
        
        // 模拟创建用户
        $newUser = [
            'id' => 3,
            'name' => $data['name'] ?? 'New User',
            'email' => $data['email'] ?? 'new@example.com'
        ];
        
        return $this->json(['message' => 'User created', 'user' => $newUser], 201);
    }
    
    public function update(Request $request) {
        $id = $request->getRouteParam('id');
        $data = $request->getBody();
        
        // 模拟更新用户
        $updatedUser = [
            'id' => $id,
            'name' => $data['name'] ?? 'Updated User',
            'email' => $data['email'] ?? 'updated@example.com'
        ];
        
        return $this->json(['message' => 'User updated', 'user' => $updatedUser]);
    }
    
    public function delete(Request $request) {
        $id = $request->getRouteParam('id');
        
        // 模拟删除用户
        return $this->json(['message' => "User $id deleted"]);
    }
    private function findUser($id) {
        // 这里应该是您的数据库查询逻辑
        // 例如: return $this->db->table('users')->where('id', '=', $id)->first();
        
        // 模拟数据
        $users = [
            1 => ['id' => 1, 'name' => 'John Doe', 'email' => 'john@example.com'],
            2 => ['id' => 2, 'name' => 'Jane Smith', 'email' => 'jane@example.com']
        ];
        
        return $users[$id] ?? null;
    }
}